<?php

namespace app\sys\controller;

use Exception;
use Ip2Region;
use think\admin\Controller;
use think\admin\model\SysOplog;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\HttpResponseException;

/**
 * 系统日志管理
 * @class Oplog
 * @package app\sys\controller
 */
class Oplog extends Controller
{
    /**
     * 系统日志管理
     * @auth true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysOplog::mQuery();
        // 数据列表搜索过滤
        $query->equal('username,action')->dateBetween('create_time');
        $query->like('content,geoip,node');
        $lists = $query->order('id desc')->page();
    }

    /**
     * 清理系统日志
     * @auth true
     */
    public function clear()
    {
        try {
            SysOplog::mQuery()->empty();
            sysoplog('日志管理', '成功清理所有日志');
            $this->success('日志清理成功！');
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (Exception $exception) {
            trace_file($exception);
            $this->error("日志清理失败，{$exception->getMessage()}");
        }
    }

    /**
     * 删除系统日志
     * @auth true
     */
    public function delete()
    {
        sysoplog('日志管理', '日志删除成功');
        SysOplog::mDelete();
    }

    /**
     * 列表数据处理
     * @param array $data
     * @throws Exception
     */
    protected function _index_page_filter(array &$data)
    {
        $region = new Ip2Region();
        foreach ($data as &$vo) {
            $vo['geoisp'] = $region->simple($vo['geoip']);
        }
    }
}
